<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${isEdit ? '编辑' : '添加'}电影 - 管理员后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
        }
        .form-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 2rem;
        }
        .required {
            color: #dc3545;
        }
        .poster-preview {
            max-width: 200px;
            max-height: 280px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body class="bg-light">
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
        <div class="container">
            <a class="navbar-brand fw-bold" href="${pageContext.request.contextPath}/admin/movies">
                <i class="fas fa-cog me-2"></i>管理员后台
            </a>

            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="${pageContext.request.contextPath}/admin/movies">
                    <i class="fas fa-arrow-left me-1"></i>返回电影管理
                </a>
                <div class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user me-1"></i>${sessionScope.user.username}
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="${pageContext.request.contextPath}/logout">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- 管理员头部 -->
    <section class="admin-header">
        <div class="container">
            <h2>
                <i class="fas fa-${isEdit ? 'edit' : 'plus'} me-2"></i>
                ${isEdit ? '编辑' : '添加'}电影
            </h2>
            <p class="mb-0">${isEdit ? '修改电影信息' : '添加新的电影到系统中'}</p>
        </div>
    </section>

    <div class="container mt-4">
        <!-- 错误信息 -->
        <c:if test="${not empty error}">
            <div class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>${error}
            </div>
        </c:if>

        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="form-card">
                    <form action="${pageContext.request.contextPath}/admin/movies" method="post" id="movieForm" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="${isEdit ? 'edit' : 'add'}">
                        <c:if test="${isEdit}">
                            <input type="hidden" name="id" value="${movie.id}">
                        </c:if>

                        <div class="row">
                            <div class="col-md-8">
                                <!-- 基本信息 -->
                                <h5 class="mb-3">基本信息</h5>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">
                                            中文片名 <span class="required">*</span>
                                        </label>
                                        <input type="text" class="form-control" name="title"
                                               value="${movie.title}" required placeholder="请输入中文片名">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">英文片名</label>
                                        <input type="text" class="form-control" name="englishTitle"
                                               value="${movie.englishTitle}" placeholder="请输入英文片名">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">
                                            导演 <span class="required">*</span>
                                        </label>
                                        <input type="text" class="form-control" name="director"
                                               value="${movie.director}" required placeholder="请输入导演姓名">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">主演</label>
                                        <input type="text" class="form-control" name="actors"
                                               value="${movie.actors}" placeholder="请输入主演，用逗号分隔">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">
                                            类型 <span class="required">*</span>
                                        </label>
                                        <select class="form-select" name="genre" required>
                                            <option value="">请选择类型</option>
                                            <option value="动作" ${movie.genre == '动作' ? 'selected' : ''}>动作</option>
                                            <option value="喜剧" ${movie.genre == '喜剧' ? 'selected' : ''}>喜剧</option>
                                            <option value="爱情" ${movie.genre == '爱情' ? 'selected' : ''}>爱情</option>
                                            <option value="科幻" ${movie.genre == '科幻' ? 'selected' : ''}>科幻</option>
                                            <option value="恐怖" ${movie.genre == '恐怖' ? 'selected' : ''}>恐怖</option>
                                            <option value="剧情" ${movie.genre == '剧情' ? 'selected' : ''}>剧情</option>
                                            <option value="动画" ${movie.genre == '动画' ? 'selected' : ''}>动画</option>
                                            <option value="悬疑" ${movie.genre == '悬疑' ? 'selected' : ''}>悬疑</option>
                                            <option value="战争" ${movie.genre == '战争' ? 'selected' : ''}>战争</option>
                                            <option value="纪录片" ${movie.genre == '纪录片' ? 'selected' : ''}>纪录片</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">
                                            时长（分钟） <span class="required">*</span>
                                        </label>
                                        <input type="number" class="form-control" name="duration"
                                               value="${movie.duration}" required min="1" max="500"
                                               placeholder="请输入电影时长">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">评分</label>
                                        <input type="text" class="form-control" name="rating"
                                               value="${movie.rating}" placeholder="如：8.5">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">上映日期</label>
                                        <input type="date" class="form-control" name="releaseDate"
                                               value="<fmt:formatDate value='${movie.releaseDate}' pattern='yyyy-MM-dd'/>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">
                                            状态 <span class="required">*</span>
                                        </label>
                                        <select class="form-select" name="status" required>
                                            <option value="">请选择状态</option>
                                            <option value="COMING_SOON" ${movie.status == 'COMING_SOON' ? 'selected' : ''}>即将上映</option>
                                            <option value="NOW_SHOWING" ${movie.status == 'NOW_SHOWING' ? 'selected' : ''}>正在热映</option>
                                            <option value="ENDED" ${movie.status == 'ENDED' ? 'selected' : ''}>已下架</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">语言</label>
                                        <input type="text" class="form-control" name="language"
                                               value="${movie.language}" placeholder="如：中文">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">制片国家/地区</label>
                                        <input type="text" class="form-control" name="country"
                                               value="${movie.country}" placeholder="如：中国">
                                    </div>
                                </div>

                                <!-- 媒体信息 -->
                                <h5 class="mb-3 mt-4">媒体信息</h5>

                                <div class="mb-3">
                                    <label class="form-label">海报图片</label>
                                    <div class="row">
                                        <div class="col-md-8">
                                            <input type="file" class="form-control" id="posterFile" name="posterFile"
                                                   accept="image/*" onchange="handleFileUpload(this)">
                                            <small class="text-muted">支持JPG、PNG、GIF格式，建议尺寸：300x400像素</small>
                                        </div>
                                        <div class="col-md-4">
                                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="uploadPoster()">
                                                <i class="fas fa-upload me-1"></i>上传图片
                                            </button>
                                        </div>
                                    </div>
                                    <div id="uploadProgress" class="progress mt-2" style="display: none;">
                                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                                    </div>
                                </div>

<%--                                <div class="mb-3">--%>
<%--                                    <label class="form-label">海报URL（可选）</label>--%>
<%--                                    <input type="url" class="form-control" name="posterUrl" id="posterUrl"--%>
<%--                                           value="${movie.posterUrl}" placeholder="或者直接输入海报图片URL"--%>
<%--                                           onchange="previewPoster(this.value)">--%>
<%--                                    <small class="text-muted">如果上传了图片，此字段将被自动填充</small>--%>
<%--                                </div>--%>

                                <div class="mb-3">
                                    <label class="form-label">预告片URL</label>
                                    <input type="url" class="form-control" name="trailerUrl"
                                           value="${movie.trailerUrl}" placeholder="请输入预告片视频URL">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">剧情简介</label>
                                    <textarea class="form-control" name="synopsis" rows="5"
                                              placeholder="请输入电影剧情简介">${movie.synopsis}</textarea>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <!-- 海报预览 -->
                                <h5 class="mb-3">海报预览</h5>
                                <div class="text-center">
                                    <img id="posterPreview"
                                         src="${movie.posterUrl != null ? movie.posterUrl : '/images/default-poster.jpg'}"
                                         class="poster-preview" alt="海报预览">
                                </div>

                                <!-- 提示信息 -->
                                <div class="mt-4">
                                    <div class="alert alert-info">
                                        <h6><i class="fas fa-info-circle me-2"></i>填写提示</h6>
                                        <ul class="mb-0 small">
                                            <li>标有 <span class="required">*</span> 的字段为必填项</li>
                                            <li>海报建议使用高清图片</li>
                                            <li>剧情简介建议控制在200字以内</li>
                                            <li>上映日期影响电影在前台的显示</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-primary btn-lg me-3">
                                <i class="fas fa-save me-2"></i>
                                ${isEdit ? '保存修改' : '添加电影'}
                            </button>
                            <a href="${pageContext.request.contextPath}/admin/movies" class="btn btn-secondary btn-lg">
                                <i class="fas fa-times me-2"></i>取消
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function previewPoster(url) {
            if (url && url.trim() !== '') {
                $('#posterPreview').attr('src', url);
            } else {
                $('#posterPreview').attr('src', '/images/default-poster.jpg');
            }
        }

        function handleFileUpload(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];

                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    alert('请选择图片文件');
                    input.value = '';
                    return;
                }

                // 验证文件大小（10MB）
                if (file.size > 10 * 1024 * 1024) {
                    alert('图片文件大小不能超过10MB');
                    input.value = '';
                    return;
                }

                // 预览图片
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#posterPreview').attr('src', e.target.result);
                };
                reader.readAsDataURL(file);
            }
        }

        function uploadPoster() {
            const fileInput = document.getElementById('posterFile');
            const file = fileInput.files[0];

            if (!file) {
                alert('请先选择要上传的图片文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            // 显示进度条
            $('#uploadProgress').show();
            $('.progress-bar').css('width', '0%');

            $.ajax({
                url: '${pageContext.request.contextPath}/admin/upload-image',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    const xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(evt) {
                        if (evt.lengthComputable) {
                            const percentComplete = (evt.loaded / evt.total) * 100;
                            $('.progress-bar').css('width', percentComplete + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    if (response.success) {
                        $('#posterUrl').val(response.url);
                        previewPoster(response.url);
                        alert('图片上传成功！');
                    } else {
                        alert('上传失败：' + response.message);
                    }
                },
                error: function() {
                    alert('上传失败，请稍后重试');
                },
                complete: function() {
                    $('#uploadProgress').hide();
                    $('.progress-bar').css('width', '0%');
                }
            });
        }

        $(document).ready(function() {
            // 表单验证
            $('#movieForm').on('submit', function(e) {
                const title = $('input[name="title"]').val().trim();
                const director = $('input[name="director"]').val().trim();
                const genre = $('select[name="genre"]').val();
                const duration = $('input[name="duration"]').val();
                const status = $('select[name="status"]').val();

                if (!title || !director || !genre || !duration || !status) {
                    e.preventDefault();
                    alert('请填写所有必填项');
                    return false;
                }

                if (duration < 1 || duration > 500) {
                    e.preventDefault();
                    alert('电影时长必须在1-500分钟之间');
                    return false;
                }
            });
        });
    </script>
</body>
</html>
